﻿using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace TestTcpClient;

/// <summary>
///     Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private CancellationTokenSource? _cancellationTokenSource;
    private NetworkStream? _stream;
    private TcpClient? _tcpClient;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Log(string message)
    {
        Dispatcher.Invoke(() =>
        {
            txtLog.AppendText($"{DateTime.Now:HH:mm:ss} - {message}\n");
            txtLog.ScrollToEnd();
        });
    }

    private async void BtnConnect_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            _cancellationTokenSource = new CancellationTokenSource();
            _tcpClient = new TcpClient();

            var ip = txtServerIP.Text;
            var port = int.Parse(txtPort.Text);

            await _tcpClient.ConnectAsync(ip, port);
            _stream = _tcpClient.GetStream();

            Log($"已连接到服务器 {ip}:{port}");

            btnConnect.IsEnabled = false;
            btnDisconnect.IsEnabled = true;

            // 开始接收数据
            _ = Task.Run(async () => await ReceiveDataAsync(_cancellationTokenSource.Token));
        }
        catch (Exception ex)
        {
            Log($"连接服务器错误: {ex.Message}");
        }
    }

    private async Task ReceiveDataAsync(CancellationToken cancellationToken)
    {
        var buffer = new byte[1024];

        try
        {
            while (!cancellationToken.IsCancellationRequested && _tcpClient!.Connected)
            {
                var bytesRead = await _stream!.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
                if (bytesRead == 0) break;

                var message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Log($"收到消息: {message}");
            }
        }
        catch (Exception ex)
        {
            Log($"接收数据错误: {ex.Message}");
        }
        finally
        {
            Log("与服务器断开连接");
            Dispatcher.Invoke(() =>
            {
                btnConnect.IsEnabled = true;
                btnDisconnect.IsEnabled = false;
            });
        }
    }

    private async void BtnSend_Click(object sender, RoutedEventArgs e)
    {
        await SendMessage();
    }

    private async void TxtMessage_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter) await SendMessage();
    }

    private async Task SendMessage()
    {
        if (_tcpClient == null || !_tcpClient.Connected)
        {
            Log("未连接到服务器");
            return;
        }

        var message = txtMessage.Text;
        if (string.IsNullOrWhiteSpace(message)) return;

        try
        {
            var data = Encoding.UTF8.GetBytes(message);
            await _stream!.WriteAsync(data, 0, data.Length);
            Log($"发送消息: {message}");
        }
        catch (Exception ex)
        {
            Log($"发送消息错误: {ex.Message}");
        }
    }

    private void BtnDisconnect_Click(object sender, RoutedEventArgs e)
    {
        _cancellationTokenSource?.Cancel();
        _tcpClient?.Close();

        Log("已断开连接");
        btnConnect.IsEnabled = true;
        btnDisconnect.IsEnabled = false;
    }

    protected override void OnClosed(EventArgs e)
    {
        _cancellationTokenSource?.Cancel();
        _tcpClient?.Close();
        base.OnClosed(e);
    }
}